﻿var assert = require("assert");
var http = require('http');
var url = require('url');
var request = require('request');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

var serviceUrl = 'http://localhost:3000/restful/file';

describe('文件测试', function () {
	var fileId = '';

	describe('#文件新建', function() {
		it('文件新建', function(done) {
			// 提交错误数据
			var postCreate400 = function() {
				var createReq = request.post(serviceUrl, function(err, res, body) {
					if (err) throw err;
					
					console.log('post create 400 code : ', res.statusCode);
					assert.equal(400, res.statusCode, '错误数据新建返回状态错误');
					postCreate();
				});
				
				var form = createReq.form();
			};
			// 提交正确数据
			var postCreate = function() {
				var filePath = path.join(__dirname, 'upload.zip');
				var md5sum = crypto.createHash('md5');
				var readStream = fs.ReadStream(filePath);
				readStream.on('data', function(d) {
					md5sum.update(d);
				}).on('end', function() {
					var md5 = md5sum.digest('hex');
					var createReq = request.post(serviceUrl, function(err, res, body) {
						if (err) throw err;
						
						console.log('post create code : ', res.statusCode);
						console.log('post create body : ', body);
						assert.equal(200, res.statusCode, '新建返回状态错误');
						assert(body, '新建没有返回结果');
						var fileInfo = JSON.parse(body);
						console.log('post create : %j', fileInfo);
						
						assert(fileInfo._id, '新建没有返回结果id');
						assert(fileInfo.md5, '新建没有返回结果md5sum');
						assert.equal(fileInfo.md5, md5, '新建返回结果md5sum和提交不符');
						assert(fileInfo.size, '新建没有返回结果size');
						
						fileId = fileInfo.id;
						
						done();
					});
					
					var form = createReq.form();
					form.append('file', fs.createReadStream(filePath));
					
				}).on('error', function(err) {
					throw err;
				});
			};
			
			postCreate400();
		});
	});
});
